﻿
using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Aop.Api.Util;
using Coldairarrow.Business;
using Coldairarrow.Entity;
using Coldairarrow.Entity.Backstage.TheRules;
using Coldairarrow.Entity.Backstage.UserData;
using Coldairarrow.Entity.BTB_StaffUsers;
using Coldairarrow.Entity.Goods;
using Coldairarrow.Entity.Pay;
using Coldairarrow.IBusiness;
using Coldairarrow.IBusiness.Pay;
using Coldairarrow.Util;
using Coldairarrow.Util.Pay.AlipayPay;
using EFCore.Sharding;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.Pay
{
    [Route("/Pay/[controller]/[action]")]
    public class OrderInfoAlipayNotify : BaseApiController
    {
        public readonly IWebHostEnvironment _webHostEnvironment;
        public OrderInfoAlipayNotify(IOperator Operators, ILogger<OrderInfoAlipayNotify> logger, IDbAccessor db, IOrder_MasterBusiness order_MasterBus, IOutbound_DetailsBusiness outbound_DetailsBusiness, IWeChatParameterBusiness weChatParameterBusiness, IWebHostEnvironment hostEnvironment)
        {
            _outbound_DetailsBusiness = outbound_DetailsBusiness;
            _webHostEnvironment = hostEnvironment;
            _Operator = Operators;
            _weChatParameterBusiness = weChatParameterBusiness;
            _order_MasterBus = order_MasterBus;
            _logger = logger;
            _DB = db;
        }
        private ILogger<OrderInfoAlipayNotify> _logger;
        private IOutbound_DetailsBusiness _outbound_DetailsBusiness { get; }
        private readonly IOperator _Operator;
        private IWeChatParameterBusiness _weChatParameterBusiness { get; }
        private IOrder_MasterBusiness _order_MasterBus { get; }
        private IDbAccessor _DB;

        public class AlyPayDTO {
            /// <summary>
            /// 外部订单号，商户网站订单系统中唯一的订单号
            /// </summary>
            public string tradeno { get; set; }

            /// <summary>
            /// 订单名称
            /// </summary>
            public string subject { get; set; }

            /// <summary>
            /// 商品描述
            /// </summary>
            public string itemBody { get; set; }

            /// <summary>
            /// 返回地址
            /// </summary>
            public string backURL { get; set; }
        }

        ///<summary>
        /// 发起支付请求
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public Entity.Pay.PayNum PayRequest([FromBody]AlyPayDTO input)
        {
            string tradeno = input.tradeno; //外部订单号，商户网站订单系统中唯一的订单号
            string subject = input.subject; //订单名称
            string totalAmout = ""; //付款金额
            string itemBody = input.itemBody; //商品描述

            #region 验证订单是否有效,并合计价格
            var data1 = _DB.GetIQueryable<Order_Master>(true).Where(q => q.Id == input.tradeno && q.PayState == 0).ToList();
            totalAmout = ((decimal)data1[0].TotalPrice).ToString("0.00");

            Serilog.Log.Information("tradeno={0}", input.tradeno.ToString());
            Serilog.Log.Information("subject={0}", input.subject.ToString());
            Serilog.Log.Information("totalAmout={0}", totalAmout);
            Serilog.Log.Information("itemBody={0}", input.itemBody.ToString());
            #endregion


            Entity.Pay.PayNum payNum = new Entity.Pay.PayNum();
            var str = "SELECT * FROM Order_Master WHERE ID = '" + tradeno + "' AND CreatorId = '" + _Operator.UserId + "'";
            var data = _DB.GetIQueryable<Order_Master>(true).Where(q => q.Id == tradeno && q.PayState == 0).ToList();

            if (data.Count() > 0)
            {
                var cert = new Config.certParams();
                //设置证书相关参数
                CertParams certParams = new CertParams
                {
                    AlipayPublicCertPath = _webHostEnvironment.WebRootPath + cert.AlipayPublicCertPath,
                    AppCertPath = _webHostEnvironment.WebRootPath + cert.AppCertPath,
                    RootCertPath = _webHostEnvironment.WebRootPath + cert.RootCertPath
                };


                DefaultAopClient client = new DefaultAopClient(Config.Gatewayurl, Config.AppId, Config.PrivateKey, "json", "2.0",
                    Config.SignType, Config.CharSet, false, certParams);

                // 组装业务参数model
                AlipayTradePagePayModel model = new AlipayTradePagePayModel();
                model.Body = itemBody;//商品描述
                model.Subject = subject;//订单名称
                model.TotalAmount = totalAmout;//付款金额
                model.OutTradeNo = tradeno;//订单号
                model.ProductCode = "FAST_INSTANT_TRADE_PAY";


                AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
                // 设置同步回调地址
                request.SetReturnUrl("https://api.leyi123.com/Pay/OrderInfoAlipayNotify/Callback");
                // 设置异步通知接收地址
                request.SetNotifyUrl("");
                // 将业务model载入到request
                request.SetBizModel(model);

                var response = client.SdkExecute(request);
                Console.WriteLine($"订单支付发起成功，订单号：{tradeno}");
                //跳转支付宝支付
                payNum.code = "200";
                payNum.msg = "操作成功";
                payNum.Success = true;
                payNum.Data1 = Config.Gatewayurl + "?" + response.Body;
                return payNum;
            }
            else
            {
                payNum.code = "202";
                payNum.msg = "该订单已被支付";
                payNum.Success = false;
                payNum.Data1 = "";
                return payNum;
            }
        }


        ///<summary>
        /// 发起支付请求
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        [NoFormatResponse]
        public string H5PhonePayRequest([FromBody] AlyPayDTO input)
        {
            string tradeno = input.tradeno; //外部订单号，商户网站订单系统中唯一的订单号
            string subject = input.subject; //订单名称
            string totalAmout = ""; //付款金额
            string itemBody = input.itemBody; //商品描述

            #region 验证订单是否有效,并合计价格
            var data1 = _DB.GetIQueryable<Order_Master>(true).Where(q => q.Id == input.tradeno).ToList();

            if (data1.Count == 0)
            {
                throw new BusException("未查询到此订单请重新下单重试！");
            }
            else if (data1.Count > 0 && data1[0].PayState > 0)
            {
                throw new BusException("此订单已支付，请勿重新支付！");
            }

            totalAmout = ((decimal)data1[0].TotalPrice).ToString("0.00");

            Serilog.Log.Information("tradeno={0}", input.tradeno.ToString());
            Serilog.Log.Information("subject={0}", input.subject.ToString());
            Serilog.Log.Information("totalAmout={0}", totalAmout);
            Serilog.Log.Information("itemBody={0}", input.itemBody.ToString());
            #endregion


            Entity.Pay.PayNum payNum = new Entity.Pay.PayNum();
            var str = "SELECT * FROM Order_Master WHERE ID = '" + tradeno + "' AND CreatorId = '" + _Operator.UserId + "'";
            var data = _DB.GetIQueryable<Order_Master>(true).Where(q => q.Id == tradeno && q.PayState == 0).ToList();

            if (data.Count() > 0)
            {
                var cert = new Config.certParams();
                //设置证书相关参数
                CertParams certParams = new CertParams
                {
                    AlipayPublicCertPath = _webHostEnvironment.WebRootPath + cert.AlipayPublicCertPath,
                    AppCertPath = _webHostEnvironment.WebRootPath + cert.AppCertPath,
                    RootCertPath = _webHostEnvironment.WebRootPath + cert.RootCertPath
                };


                DefaultAopClient client = new DefaultAopClient(Configs.gatewayUrl, Configs.app_id, Configs.private_key, "json", "2.0",
                   Configs.sign_type, Configs.charset, false, certParams);

                // 组装业务参数model
                AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
                model.Body = itemBody;
                model.Subject = subject;
                model.TotalAmount = totalAmout;
                //model.TotalAmount = "0.01";
                model.OutTradeNo = tradeno;
                model.ProductCode = "QUICK_WAP_WAY";
                model.QuitUrl = input.backURL;

                //model.ProductCode = "FAST_INSTANT_TRADE_PAY";

 

                AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
                // 设置同步回调地址
                request.SetReturnUrl("https://api.leyi123.com/Pay/OrderInfoAlipayNotify/Callback");
                // 设置异步通知接收地址
                request.SetNotifyUrl("");
                // 将业务model载入到request
                // 将业务model载入到request
                request.SetBizModel(model);

                AlipayTradeWapPayResponse response = null;
                response = client.pageExecute(request, null, "post");
                Console.WriteLine($"订单支付发起成功，订单号：{tradeno}");
                //跳转支付宝支付
                //payNum.code = "200";
                //payNum.msg = "操作成功";
                //payNum.Success = true;
                //payNum.Data1 = response.Body;
                return response.Body;;
            }
            else
            {
                //payNum.code = "202";
                //payNum.msg = "该订单已被支付";
                //payNum.Success = false;
                //payNum.Data1 = "";
                return "该订单已被支付";
            }
        }


        /// <summary>
        /// 支付同步回调
        /// </summary>
        [HttpGet]
        [NoCheckJWT]
        public async Task<ActionResult> Callback()
        {
            _logger.LogInformation("回调开始+++++++++++++++++++++++" + this.GetType().ToString());
            /* 实际验证过程建议商户添加以下校验。
			1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
			2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
			3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
			4、验证app_id是否为该商户本身。
			*/

            Dictionary<string, string> sArray = GetRequestGet();
            var total_amount = sArray["total_amount"].ToString();
            _logger.LogInformation("订单价格" + total_amount);
            var out_trade_no = sArray["out_trade_no"].ToString();
            _logger.LogInformation("商户订单号" + out_trade_no);
            var trade_no = sArray["trade_no"].ToString();
            _logger.LogInformation("支付宝交易号" + trade_no);
            List<Order_Master> aa = _DB.GetIQueryable<Order_Master>(true).Where(q => q.Id == out_trade_no).ToList();

            _logger.LogInformation("订单价格" + aa[0].TotalPrice);
            if (aa[0].TotalPrice != Convert.ToDecimal(total_amount))
            {
                _logger.LogInformation("订单价格出现异常，请联系管理员" + aa[0].TotalPrice);

                string url2 = ConfigurationUtil.GetSection("Indentity:zfbntferrorurl");
                Response.Redirect(url2);
                //throw new BusException("订单价格出现异常，请联系管理员", errorCode: -1);
            }
            _logger.LogInformation("订单号" + aa[0].Id);
            if (aa[0].Id != out_trade_no)
            {
                _logger.LogInformation("订单号出现异常，请联系管理员" + aa[0].Id);

                string url2 = ConfigurationUtil.GetSection("Indentity:zfbntferrorurl");
                Response.Redirect(url2);
                //throw new BusException("订单号出现异常，请联系管理员", errorCode: -1);
            }
            _logger.LogInformation("sArray=" + sArray.ToJson().ToString());
            _logger.LogInformation("sArray.Count=" + sArray.Count);
            if (sArray.Count != 0)
            {
                try {

                    bool flag = false;
                    var cert = new Config.certParams();

                    string aliPublicCertPath = _webHostEnvironment.WebRootPath + cert.AlipayPublicCertPath;

                    flag = AlipaySignature.RSACertCheckV1(sArray, aliPublicCertPath, Configs.charset, Configs.sign_type);
                    _logger.LogInformation("bool Aliflag=" + flag);
                    if (flag)
                    {
                        aa[0].OrderState = 1;
                        aa[0].PayState = 1;
                        await _order_MasterBus.UpdateDataAsync(aa[0]);
                        List<Outbound_Details> bb = _DB.GetIQueryable<Outbound_Details>(true).Where(q => q.OrderMater_Id == out_trade_no).ToList();
                        int count = bb.Count();
                        _logger.LogInformation("参数量" + count);
                        if (count > 0)
                        {
                            bb[0].Bound_Flag = 2;
                            await _outbound_DetailsBusiness.UpdateDataAsync(bb[0]);
                            if (out_trade_no != null)
                            {
                                string key = RedisHelper.Get("Order:" + out_trade_no);
                                RedisHelper.Del(key);
                            }
                        }
                        WeChatParameter data = new WeChatParameter()
                        {
                            Id = IdHelper.GetId(),
                            out_trade_no = trade_no,
                            _SumMoney = Convert.ToDecimal(total_amount),
                            _Orderid = out_trade_no,
                            transaction_id = out_trade_no,
                            PayMode = 1
                        };
                        await _weChatParameterBusiness.AddDataAsync(data);
                        await stock(out_trade_no);
                        _logger.LogInformation("回调成功+++++++++++++++++++++++");

                        #region//分销代码
                        //查询上级人员
                        var theUser = _DB.GetIQueryable<BTB_StaffUser>().Where(x => x.id.Equals(aa[0].CreatorId)).ToList();
                        if (theUser.Count > 0)
                        {
                            var sjUser = _DB.GetIQueryable<BTB_StaffUser>().Where(x => x.User_YQCode.Equals(theUser[0].User_BYQCode)).ToList();
                            if (sjUser.Count > 0)
                            {
                                //获取所有商品
                                var gList = _DB.GetIQueryable<Order_Decimal>().Where(x => x.OrderMaster_Id.Equals(aa[0].Id)).ToList();
                                int syNum = 0;

                                //查询默认返利折扣
                                int dsCount = 0;
                                var dfList = _DB.GetIQueryable<BS_Rebate>().Where(x => x.GoodsId.Equals("****") && x.IsDefault).ToList();
                                if (dfList.Count > 0)
                                {
                                    dsCount = (int)dfList[0].ReturnDiscount;
                                }
                                List<BS_UserRebate> uList = new List<BS_UserRebate>();
                                foreach (var item in gList)
                                {
                                    //查询商品返利折扣
                                    var dgfList = _DB.GetIQueryable<BS_Rebate>().Where(x => x.GoodsId.Equals(item.Product_Id) && x.IsDefault).ToList();
                                    if (dgfList.Count > 0)
                                    {
                                        dsCount = (int)dgfList[0].ReturnDiscount;
                                    }

                                    if (dsCount > 0)
                                    {
                                        int rMoney = (int)(((decimal)item.SumProducts * dsCount) / 100);
                                        if (rMoney > 0)
                                        {
                                            BS_UserRebate model = new BS_UserRebate();
                                            model.Id = IdHelper.GetId();
                                            model.Deleted = false;
                                            model.CreatorId = theUser[0].id;
                                            model.CreateTime = DateTime.Now;
                                            model.SUserId = sjUser[0].id;
                                            model.XFUserId = theUser[0].id;
                                            model.OrderId = aa[0].Id;
                                            model.GoodsId = item.Products_Id;
                                            model.GoodsName = item.ProductNames;
                                            model.GoodsItemName = item.ProductitemNames;
                                            model.GoodsPrice = item.ProductPrice;
                                            model.GoodsNum = item.Products_Num;
                                            model.ReturnDiscount = dsCount;
                                            model.OrderMoney = (decimal)item.SumProducts;
                                            model.Type = 0;
                                            model.Note = theUser[0].NickName.Substring(0,1)+"*购买"+ item.ProductitemNames+"收益";
                                            model.ReturnMoney = rMoney;
                                            syNum += rMoney;
                                            uList.Add(model);
                                        }

                                        var upMList = _DB.GetIQueryable<BS_UserICPoint>().Where(x => x.UserId.Equals(sjUser[0].id)).ToList();
                                        if (upMList.Count > 0)
                                        {
                                            upMList[0].Income += syNum;

                                            await _DB.UpdateAsync(upMList[0]);
                                            await _DB.InsertAsync(uList);
                                        }
                                        else
                                        {
                                            BS_UserICPoint upModel = new BS_UserICPoint();
                                            upModel.Id = IdHelper.GetId();
                                            upModel.Deleted = false;
                                            upModel.CreatorId = theUser[0].id;
                                            upModel.CreateTime = DateTime.Now;
                                            upModel.UserId = sjUser[0].id;
                                            upModel.Income = syNum;
                                            upModel.Point = 0;

                                            await _DB.InsertAsync(upModel);
                                            await _DB.InsertAsync(uList);
                                        }


                                    }

                                }


                            }
                        }

                        #endregion

                        string url = ConfigurationUtil.GetSection("Indentity:zfbntfurl");
                        Response.Redirect(url);
                        //return Content("<xml><return_code>FAIL</return_code><return_msg>支付成功OK</return_msg></xml>");
                    }
                    else
                    {
                        //Console.WriteLine($"同步验证失败，订单号：{sArray["out_trade_no"]}");
                        //ViewData["PayResult"] = "同步验证失败";
                        string url = ConfigurationUtil.GetSection("Indentity:zfbntferrorurl");
                        Response.Redirect(url);
                        //return Content("<xml><return_code>FAIL</return_code><return_msg>支付失败</return_msg></xml>");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("ex.Message=" + ex.Message);
                    string url = ConfigurationUtil.GetSection("Indentity:zfbntferrorurl");
                    Response.Redirect(url);
                   
                    //return Content("<xml><return_code>FAIL</return_code><return_msg>" + ex.Message + "</return_msg></xml>");
                }
                
            }
            return Content("<xml><return_code>FAIL</return_code><return_msg>出现异常，请联系管理员</return_msg></xml>");

        }

        /// <summary>
        /// 订单查询
        /// </summary>
        /// <param name="tradeno"></param>
        /// <param name="alipayTradeNo"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public string Query(string tradeno, string alipayTradeNo)
        {
            var cert = new Config.certParams();
            //设置证书相关参数
            CertParams certParams = new CertParams
            {
                AlipayPublicCertPath = _webHostEnvironment.WebRootPath + cert.AlipayPublicCertPath,
                AppCertPath = _webHostEnvironment.WebRootPath + cert.AppCertPath,
                RootCertPath = _webHostEnvironment.WebRootPath + cert.RootCertPath
            };


            DefaultAopClient client = new DefaultAopClient(Configs.gatewayUrl, Configs.app_id, Configs.private_key, "json", "2.0",
               Configs.sign_type, Configs.charset, false, certParams);
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            model.OutTradeNo = tradeno;
            model.TradeNo = alipayTradeNo;

            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.SetBizModel(model);

            var response = client.Execute(request);
            return response.Body;
        }

        #region 解析请求参数

        private Dictionary<string, string> GetRequestGet()
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();

            ICollection<string> requestItem = Request.Query.Keys;
            foreach (var item in requestItem)
            {
                sArray.Add(item, Request.Query[item]);

            }
            return sArray;

        }

        private Dictionary<string, string> GetRequestPost()
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();

            ICollection<string> requestItem = Request.Form.Keys;
            foreach (var item in requestItem)
            {
                sArray.Add(item, Request.Form[item]);

            }
            return sArray;

        }

        #endregion
        public async Task stock(string id)
        {
            var data = _DB.GetIQueryable<Order_Decimal>(true).Where(q => q.OrderMaster_Id == id).ToList();
            _logger.LogInformation("商品数据" + data.ToJson().ToString());
            foreach (var item in data)
            {
                var aa = item.Product_Id;
                _logger.LogInformation("商品+++++++++++++id" + aa);
                var Product = _DB.GetIQueryable<BTB_Goods>(true).FirstOrDefault(q => q.ID == item.Product_Id);
                _logger.LogInformation("回调成功+++++++++++++++++++++++" + Product.ToJson().ToString());
                var Products = _DB.GetIQueryable<BTB_GoodsSpecificationsItem>(true).FirstOrDefault(q => q.GoodsSpecificationsItemID == item.Products_Id);          
                _logger.LogInformation("回调成功+++++++++++++++++++++++" + Products.ToJson().ToString());
                Product.SaleCount += (int)item.Products_Num;
                _logger.LogInformation("回调成功+++++++++++++++++++++++" + Product.SaleCount);
                if (!Products.IsNullOrEmpty())
                {
                    Products.Inventory = (int)Products?.Inventory - (int)item?.Products_Num;
                    _logger.LogInformation("回调成功+++++++++++++++++++++++" + Products.Inventory);
                    await _DB.UpdateAsync<BTB_GoodsSpecificationsItem>(Products);
                }
               
                await _DB.UpdateAsync<BTB_Goods>(Product);
            }
        }



        /// <summary>
        /// 订单退款
        /// </summary>
        /// <param name="data">退款原因</param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public string Refund(Refund data)
        {
            var cert = new Config.certParams();
            //设置证书相关参数
            CertParams certParams = new CertParams
            {
                AlipayPublicCertPath = _webHostEnvironment.WebRootPath + cert.AlipayPublicCertPath,
                AppCertPath = _webHostEnvironment.WebRootPath + cert.AppCertPath,
                RootCertPath = _webHostEnvironment.WebRootPath + cert.RootCertPath
            };


            DefaultAopClient client = new DefaultAopClient(Configs.gatewayUrl, Configs.app_id, Configs.private_key, "json", "2.0",
               Configs.sign_type, Configs.charset, false, certParams);

            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.OutTradeNo = data.tradeno;
            model.OutRequestNo = data.out_request_no;
            model.RefundAmount = data.refundAmount;
            model.RefundReason = data.out_request_no;

            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.SetBizModel(model);

            var response = client.Execute(request);
            _logger.LogInformation("支付宝交易号" + request);
            JObject studentsJson = JObject.Parse(response.Body);
            string aa = studentsJson["alipay_trade_refund_response"]["code"].ToString();
            if (aa == "10000")
            {

            }
            return aa;
        }
        public string GetJosn(string json, string key)
        {
            JObject obj = JObject.Parse(json);
            foreach (var x in obj)
            {
                if (x.Key.Equals(key))
                {
                    return x.Value.ToString();
                }
            }
            return "";
        }
     
        /// <summary>
        /// 退款查询
        /// </summary>
        /// <param name="tradeno">商户订单号</param>
        /// <param name="alipayTradeNo">支付宝交易号</param>
        /// <param name="refundNo">退款单号</param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public string RefundQuery(string tradeno, string alipayTradeNo, string refundNo)
        {
            var cert = new Config.certParams();
            //设置证书相关参数
            CertParams certParams = new CertParams
            {
                AlipayPublicCertPath = _webHostEnvironment.WebRootPath + cert.AlipayPublicCertPath,
                AppCertPath = _webHostEnvironment.WebRootPath + cert.AppCertPath,
                RootCertPath = _webHostEnvironment.WebRootPath + cert.RootCertPath
            };


            DefaultAopClient client = new DefaultAopClient(Configs.gatewayUrl, Configs.app_id, Configs.private_key, "json", "2.0",
               Configs.sign_type, Configs.charset, false, certParams);

            if (string.IsNullOrEmpty(refundNo))
            {
                refundNo = tradeno;
            }

            AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
            model.OutTradeNo = tradeno;
            model.TradeNo = alipayTradeNo;
            model.OutRequestNo = refundNo;

            AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
            request.SetBizModel(model);

            var response = client.Execute(request);
            _logger.LogInformation("支付宝交易号" + request);
            return response.Body.ToString();
        }



       //public string Main(string[] args)
       // {
       //     FileStream fs = null;
       //     string filePath = "C:\\file1.txt";
       //     //将待写的入数据从字符串转换为字节数组  
       //     Encoding encoder = Encoding.UTF8;
       //     byte[] bytes = encoder.GetBytes("Hello World! \n\r");
       //     try
       //     {
       //         fs = File.OpenWrite(filePath);
       //         //设定书写的开始位置为文件的末尾  
       //         fs.Position = fs.Length;
       //         //将待写入内容追加到文件末尾  
       //         fs.Write(bytes, 0, bytes.Length);
       //     }
       //     catch (Exception ex)
       //     {
       //         Console.WriteLine("文件打开失败{0}", ex.ToString());
       //     }
       //     finally
       //     {
       //         fs.Close();
       //     }
       //     Console.ReadLine();
       // }
    }
}
